<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-if="isLoading" type="circle" :percentage="percentage" class="progress" />
  </el-upload>
</template>

<script>
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDvlQsHWXLwW7igT0OepobBZjeLyQdampo', // 身份识别 ID
  SecretKey: 'sKcoxxlOo376tVtBF751nLhszvhP6e09' // 身份秘钥
})
export default {
  name: 'ImgUpload',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      isLoading: false,
      percentage: 0
    }
  },
  // 当imgUrl发生改变对imageUrl赋值
  watch: {
    value(val, oldVal) {
      this.imageUrl = val
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    upload(obj) {
      // obj：上传的相关信息
      // obj.file 就是我们选择的文件
      console.log(obj)
      if (obj.file) {
        this.isLoading = true
        // 上传到腾讯云
        cos.putObject({
          Bucket: 'yyb666-1304410142', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-beijing', /* 存储桶所在地域，例如 ap-beijing，必须字段 */
          Key: obj.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: obj.file, // 上传文件对象
          onProgress: (progressData) => { // 上传进度
            this.percentage = progressData.percent * 100
            // console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            // data.Location 就是返回的图片地址
            this.imageUrl = `https:${data.Location}`
            this.$emit('input', this.imageUrl)
            setTimeout(() => {
              this.isLoading = false
            }, 500)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #fff;
}
</style>
